<%@ Application Language="C#" %>

<script RunAt="server">

  private string _ApplicationPath = (HttpRuntime.AppDomainAppVirtualPath.Length > 1) ? HttpRuntime.AppDomainAppVirtualPath : String.Empty;

  private string HandleTilde(string url)
  {
    if (String.IsNullOrEmpty(url))
      return url;
    if (url.StartsWith("^~/"))
      return "^" + _ApplicationPath + url.Substring("^~/".Length - 1);
    if (url.StartsWith("~/"))
      return _ApplicationPath + url.Substring("~/".Length - 1);
    return url;
  }

  void Application_Start(Object sender, EventArgs e)
  {
    // Code that runs on application startup
  }

  void Application_BeginRequest(Object sender, EventArgs e)
  {
    // The following code performs URL rewriting for
    //  MyPageMethods.Products.FrmProduct.TestUrlFormat() and
    //  MyPageMethods.Products.FrmProduct.TestUrlFormatWithPost() 

    const string PATTERN = "^~/SampleUrl/(.*)/(.*).aspx$";
    const string PATTERN_FOR_POST = "^~/SampleUrlWithPost/(.*).aspx$";

    string newUrl;
    Regex regex;

    // Handle TestUrlFormat()
    regex = new Regex(HandleTilde(PATTERN));
    if (regex.IsMatch(Request.RawUrl))
    {
      newUrl = regex.Replace(Request.RawUrl, "~/Products/FrmProduct.aspx?" + MetaSapiens.PageMethods.PageMethodsEngine.PARAM_Method + "=$1&param=$2");
      newUrl = HandleTilde(newUrl);
    }
    else
    {
      // Handle TestUrlFormatWithPost()
      regex = new Regex(HandleTilde(PATTERN_FOR_POST));
      if (regex.IsMatch(Request.RawUrl))
      {
        newUrl = "~/Products/FrmProduct.aspx";
      }
      else
      {
        // Other method or URL
        newUrl = Request.RawUrl;
      }
    }

    // Handle HTTP POST
    newUrl = MetaSapiens.PageMethods.PageMethodsEngine.AddPostData(newUrl, Request);

    // Update the path
    Context.RewritePath(newUrl, false);
  }

  void Application_End(Object sender, EventArgs e)
  {
    //  Code that runs on application shutdown

  }

  void Application_Error(Object sender, EventArgs e)
  {
    // Code that runs when an unhandled error occurs

  }

  void Session_Start(Object sender, EventArgs e)
  {
    // Code that runs when a new session is started

  }

  void Session_End(Object sender, EventArgs e)
  {
    // Code that runs when a session ends. 
    // Note: The Session_End event is raised only when the sessionstate mode
    // is set to InProc in the Web.config file. If session mode is set to StateServer 
    // or SQLServer, the event is not raised.

  }
       
</script>